package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.LocationDao;
import com.itheima.dao.MemberDao;
import com.itheima.dao.OrderDao;
import com.itheima.dao.OrderSettingDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.CheckItem;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderService;
import com.itheima.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 体检预约服务
 */
@Service(interfaceClass = OrderService.class)
@Transactional
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderSettingDao orderSettingDao;
    @Autowired
    private MemberDao memberDao;
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private LocationDao locationDao;

    //体检预约微信端预约方法
    public Result order(Map map) throws Exception {
        //1、检查用户所选择的预约日期是否已经提前进行了预约设置，如果没有设置则无法进行预约
        String orderDate = (String) map.get("orderDate");//预约日期
        OrderSetting orderSetting = orderSettingDao.findByOrderDate(DateUtils.parseString2Date(orderDate));
        if (orderSetting == null) {
            //指定日期没有进行预约设置，无法完成体检预约
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }

        //2、检查用户所选择的预约日期是否已经约满，如果已经约满则无法预约
        int number = orderSetting.getNumber();//可预约人数
        int reservations = orderSetting.getReservations();//已预约人数
        if (reservations >= number) {
            //已经约满，无法预约
            return new Result(false, MessageConstant.ORDER_FULL);
        }

        //3、检查用户是否重复预约（同一个用户在同一天预约了同一个套餐），如果是重复预约则无法完成再次预约
        String telephone = (String) map.get("telephone");//获取用户页面输入的手机号
        Member member = memberDao.findByTelephone(telephone);
        if (member != null) {
            //判断是否在重复预约
            Integer memberId = member.getId();//会员ID
            Date order_Date = DateUtils.parseString2Date(orderDate);//预约日期
            String setmealId = (String) map.get("setmealId");//套餐ID
            Order order = new Order(memberId, order_Date, Integer.parseInt(setmealId));
            //根据条件进行查询
            List<Order> list = orderDao.findByCondition(order);
            if (list != null && list.size() > 0) {
                //说明用户在重复预约，无法完成再次预约
                return new Result(false, MessageConstant.HAS_ORDERED);
            }
        } else {
            //4、检查当前用户是否为会员，如果是会员则直接完成预约，如果不是会员则自动完成注册并进行预约
            member = new Member();
            member.setName((String) map.get("name"));
            member.setPhoneNumber(telephone);
            member.setIdCard((String) map.get("idCard"));
            member.setSex((String) map.get("sex"));
            member.setRegTime(new Date());
            memberDao.add(member);//自动完成会员注册
        }

        //5、预约成功，更新当日的已预约人数
        //先查询预约地址ID
        Integer locationId = locationDao.findLocationIdByLocation((String)map.get("location"));
        Order order = new Order();
        order.setLocationId(locationId);
        order.setMemberId(member.getId());//设置会员ID
        order.setOrderDate(DateUtils.parseString2Date(orderDate));//预约日期
        order.setOrderType((String) map.get("orderType"));//预约类型
        order.setOrderStatus(Order.ORDERSTATUS_NO);//到诊状态
        order.setSetmealId(Integer.parseInt((String) map.get("setmealId")));//套餐ID
        orderDao.add(order);

        orderSetting.setReservations(orderSetting.getReservations() + 1);//设置已预约人数+1
        orderSettingDao.editReservationsByOrderDate(orderSetting);

        return new Result(true, MessageConstant.ORDER_SUCCESS, order.getId());
    }

    @Override
    public Result orderByTel(Map<String,String> map, Integer[] setmealIds) throws Exception {
        //本方法对人工客服要求较高  需要人工电话时判断是否会爆预约数
        //判断是否为重复预约(通过预约列表的条件查询来客户预约信息)
        String orderDate = (String) map.get("orderDate");//预约日期
        OrderSetting orderSetting = orderSettingDao.findByOrderDate(DateUtils.parseString2Date(orderDate));
        //判断当前电话号码是否为会员
        String telephone = (String) map.get("telephone");
        Member member = memberDao.findByTelephone(telephone);
        if (member == null) {
            //说明当前号码还未注册过会员
            member = new Member();
            member.setName((String) map.get("name"));
            member.setPhoneNumber(telephone);
            member.setIdCard((String) map.get("idCard"));
            member.setSex((String) map.get("sex"));
            member.setRegTime(new Date());
            member.setAge(Integer.parseInt((String) map.get("age")));
            member.setBirthday(DateUtils.parseString2Date((String) map.get("birthday")));
            member.setMarriageStatus((String) map.get("marriageStatus"));
            memberDao.add(member);//自动完成会员注册
        }


        Order order = new Order();
        order.setMemberId(member.getId());//设置会员ID
        order.setOrderDate(DateUtils.parseString2Date(orderDate));//预约日期
        order.setOrderType((String) map.get("orderType"));//预约类型
        order.setOrderStatus(Order.ORDERSTATUS_NO);//到诊状态
        order.setLocationId(Integer.parseInt((String) map.get("locationId")));
        for (Integer setmealId : setmealIds) {
            order.setSetmealId(setmealId);
            orderDao.add(order);
        }
        //预约成功，更新当日的已预约人数(一个套餐算一个人)//先查询当天预约设置
        orderSetting.setReservations(orderSetting.getReservations() + setmealIds.length);//设置已预约人数+1
        orderSettingDao.editReservationsByOrderDate(orderSetting);
        return new Result(true, MessageConstant.ORDER_SUCCESS);
    }

    //根据预约ID查询预约相关信息（体检人姓名、预约日期、套餐名称、预约类型）
    public Map findById(Integer id) throws Exception {
        Map map = orderDao.findById4Detail(id);
        if (map != null) {
            //处理日期格式
            Date orderDate = (Date) map.get("orderDate");
            map.put("orderDate", DateUtils.parseDate2String(orderDate));
        }
        return map;
    }

    @Override
    public PageResult findOrderByPage(QueryPageBean queryPageBean) {
        //根据查询条件(条件可有可无)查询预约信息
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();//查询条件
        //完成分页查询，基于mybatis框架提供的分页助手插件完成
        PageHelper.startPage(currentPage, pageSize);
        Page<Map<String, Object>> page = orderDao.findByQueryString(queryString);
        long total = page.getTotal();
        List<Map<String, Object>> rows = page.getResult();
        return new PageResult(total, rows);
    }

    /**
     * 根据 orderId 查询 手机号 和 预约日期
     *
     * @param orderId
     * @return
     */
    @Override
    public Map find2DetailsById(Integer orderId) throws Exception {
        Map map = orderDao.find2DetailsById(orderId);
        if (map != null) {
            Date orderDate = (Date) map.get("orderDate");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String format = sdf.format(orderDate);
            String orderTime = format.substring(2);
            map.put("orderDate", orderTime);
        }
        return map;
    }

    /**
     * 取消预约后,更新当日的已预约人数 - 1
     *
     * @param orderId
     * @param orderDate
     */
    @Override
    public void cancelOrder(Integer orderId, String orderDate) throws Exception {
        // 根据id删除预约
        orderDao.cancelOrder(orderId);
        // 根据日期查询当天的预约设置
        OrderSetting orderSetting = orderSettingDao.findOrderSettingByOrderDate(orderDate);
        int reservations = orderSetting.getReservations();
        // 减少当天已预约人数
        this.reduceReservations(reservations, orderDate);
    }

    /**
     * 更新当日的已预约人数 - 1
     */
    public void reduceReservations(Integer reservations, String orderDate) {
        // 更新 t_ordersetting 表
        Map<String, Object> orderSettingMap = new HashMap<String, Object>();
        Integer newReservations = reservations - 1;
        orderSettingMap.put("reservations", newReservations);
        orderSettingMap.put("orderDate", orderDate);
        orderSettingDao.updateReservations(orderSettingMap);
    }
}
